package com.joelemon.mockinfluxdbdata.mock.service.insertImpl;

import com.joelemon.mockinfluxdbdata.common.SystemException;
import com.joelemon.mockinfluxdbdata.mock.ConnectConfig;
import com.joelemon.mockinfluxdbdata.mock.DataLine;
import com.joelemon.mockinfluxdbdata.mock.service.DBInsertService;
import com.joelemon.mockinfluxdbdata.utils.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Description: http实现
 * @Author: HJY
 * @Date: 2023/11/16
 */
@Slf4j
@Service("httpInsert")
public class DBHttpInsertService implements DBInsertService {
    public static final Predicate<Integer> SUCCESS = i -> i != null && i == 204;

    private final static List<String> protocols = Arrays.asList("http", "https");

    @Override
    public int insertData(ConnectConfig connectConfig, List<DataLine> dataLines) {
        if (!protocols.contains(connectConfig.getProtocol())) {
            throw new SystemException("不支持的协议:" + connectConfig.getProtocol());
        }
        String prefix = connectConfig.getProtocol() + "://";
        String url = prefix + connectConfig.getIp() + ":" + connectConfig.getPort() + "/write?db=" + connectConfig.getDatabase() +
                "&precision=ns&u=" + connectConfig.getUsername() + "&p=" + connectConfig.getPassword() + "&rp=" + connectConfig.getRetentionPolicy();
        int count = 0;
        for (DataLine dataLine : dataLines) {
            if (!dataLine.check()) continue;
            String tagStr = dataLine.getTagMap().entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue())
                    .collect(Collectors.joining(","));
            String filedStr = dataLine.getFieldMap().entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue())
                    .collect(Collectors.joining(" "));
            String dataStr = dataLine.getMeasurement() + "," + tagStr + " " + filedStr + " " + dataLine.getTime().getTime() + "000000";
            log.debug("数据插入：" + dataStr);
            try {
                String postRawParams = OkHttpUtil.postRawParams(url, dataStr, OkHttpUtil.TEXT, SUCCESS, v1 -> v1);
                log.debug("数据插入结果：" + postRawParams);
                count++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return count;
    }
}
